package cageballclient;

import cageballcommon.messages.Action;
import cageballcommon.messages.InitTeam;
import cageballcommon.exceptions.CageballIOException;
import cageballcommon.exceptions.CageballParseException;
import cageballcommon.io.interfaces.CageballIO;
import cageballcommon.io.impl.CageballSocketIO;
import java.io.IOException;
import java.net.Socket;
import java.util.Properties;
import cageballcommon.messages.Player;
import cageballcommon.messages.State;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Client implements Runnable {

    private AI ai;
    private String ip;
    private int port;
    private InitTeam otherTeam;
    private CageballIO io;

    public Client(String ip, int port, AI ai) {
        this.ai = ai;
        this.ip = ip;
        this.port = port;
    }

    public void run() {
        State state;
        Properties prop;
        while (true) {
            try {
                io = new CageballSocketIO(new Socket(ip, port));
                prop = io.readProperties();

                io.writeInitTeam(ai.initMyTeam(prop));
                while (true) {
                    
                    otherTeam = io.readInitTeam();
                    ai.initOtherTeam(otherTeam);

                    while (true) {
                      
                        state = io.readState();

                        if (state.getInfo() != null) {
                            if (state.getInfo().getWinner() != null) {
                                break;
                            }
                        }

                        ai.act(state);

                        Action actions = new Action();
                        for (Player p : state.getMyTeam().getPlayers()) {
                            actions.addAction(p.getAction());
                            p.resetAction();
                        }
                        io.writeAction(actions);
                    }
                }

            } catch (CageballParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (CageballIOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Reconnecting...");
        }
    }
}
